package com.jetinno.file

import android.app.AlertDialog
import android.content.DialogInterface
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.jetinno.file.databinding.ActivityTextBinding
import com.jetinno.simple.SimpleActivity
import com.jetinno.simple.utils.FileUtil
import com.jetinno.simple.utils.ToastUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * Created by zhangyuncai on 2021/11/12.
 */
class TextActivity : SimpleActivity() {
    private val filePath: String by lazy {
        intent.getStringExtra("data")!!
    }
    private val file: File by lazy { File(filePath) }
    private var childFragment: TxtFragment? = null
    private lateinit var mDB: ActivityTextBinding

    override fun useDatabing(): Boolean {
        mDB = DataBindingUtil.setContentView(this, getLayoutId())
        return true
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_text
    }

    override fun initView() {
        addTxtFragment()

    }

    override fun initEvent() {
        mDB.headbar.setBackClickListener {
            close()
        }
        mDB.headbar.getTitleView().setOnClickListener {
            val view = window.peekDecorView()
            if (view != null) {
                val inputmanger = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                inputmanger.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }
        mDB.headbar.getTitleView().setText(file.name)
        mDB.headbar.setLeftClickListener {
            childFragment?.isEdit = true
        }
    }

    val isEdit: Boolean
        get() = childFragment?.isEdit ?: false

    override fun initData() {
    }

    private fun addTxtFragment() {
        childFragment = TxtFragment()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_text_container, childFragment!!)
            .commit()
    }

    var fileContent: String
        /**
         * 打开文件
         *
         * @return
         */
        get() {
            val lines = FileUtil.fileToLines(file)
            return TextUtils.join("\n", lines)
        }
        /**
         * 保存文件
         *
         * @param newContent
         */
        set(newContent) {
            lifecycleScope.launch(Dispatchers.IO) {
                val success = FileUtil.stringToFile(file, newContent)
                withContext(Dispatchers.Main) {
                    if (success) {
                        ToastUtil.showToast("Save Success : ${filePath}")
                    } else {
                        ToastUtil.showToast("Save Fail")
                    }
                    finish()
                }
            }
        }

    private fun close() {
        if (!isEdit) {
            finish()
            return
        }
        AlertDialog.Builder(this)
            .setMessage("Save?")
            .setPositiveButton("Yes", object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface, which: Int) {
                    if (childFragment is TxtFragment) {
                        val txtFragment = childFragment as TxtFragment
                        fileContent = txtFragment.editContent
                    } else {
                        Log.i(TAG, "Yes")
                        finish()
                    }
                }
            })
            .setNegativeButton("No") { dialog, which ->
                Log.i(TAG, "No")
                finish()
            }
            .create()
            .show()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close()
        }
        return false
    }

}
